/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yunhoo.asset.bean;

import com.yunhoo.asset.model.Asset;
import com.yunhoo.asset.util.PayCodeConstants;
import com.yunhoo.sys.db.util.IbatisTemplate;
import com.yunhoo.sys.util.common.LoginParam;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFooter;
import org.apache.poi.hssf.usermodel.HSSFHeader;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CreationHelper;

@ManagedBean(name = "assetQueryBean")
@SessionScoped
public class AssetQueryBean {

    private final String NAMESPACE = "psncard.";
    private Asset asset = new Asset();
    private List<Asset> assetlist = new ArrayList<Asset>();
    private String assetName = "";
    private List<String> allAssetName = null;
    private List<SelectItem> seleli = new ArrayList<SelectItem>();

    public AssetQueryBean() {
        initAssetName();
    }

    private void initAssetName() {
        allAssetName = IbatisTemplate.queryForList(NAMESPACE + "queryAllAssetName", LoginParam.getOrg().getCode());
        for (String a : allAssetName) {
            seleli.add(new SelectItem(a));
        }
    }

    public void queryList() {
        if (assetlist != null && assetlist.size() > 0) {
            assetlist.clear();
        }
        Map map = new HashMap();
        map.put("orgCode", LoginParam.getOrg().getCode());
        map.put("iyear", LoginParam.getIyear());
        map.put("deptcode", asset.getDept().getCode());
        map.put("cpsn_name", asset.getPerson().getCpsn_name());
        map.put("assetName", asset.getAssetName());
        map.put("priceB", asset.getPriceB());
        map.put("priceE", asset.getPriceE());
        map.put("purchDateB", asset.getPurchDateB());
        map.put("purchDateE", asset.getPurchDateE());
        map.put("shelfLifeB", asset.getShelfLifeB());
        map.put("shelfLifeE", asset.getShelfLifeE());
        assetlist = IbatisTemplate.queryForList(NAMESPACE + "queryForAsset", map);
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void exportExcel() {
        HSSFWorkbook demoWorkBook = new HSSFWorkbook();
        HSSFSheet demoSheet = demoWorkBook.createSheet("资产列表");
        String[] excelColumns = initTabeleHeader();
        List<Asset> rows = assetlist;

        HSSFHeader header = demoSheet.getHeader();
        header.setCenter("资产列表");
        HSSFRow headerRow = demoSheet.createRow(0);
        for (int i = 0; i < excelColumns.length; i++) {
            HSSFCell headerCell = headerRow.createCell((short) i);
            //headerCell.setEncoding(HSSFCell.ENCODING_UTF_16);
            headerCell.setCellValue(excelColumns[i]);
        }
        //填充数据
        int rowIndex = 1;
        for (Asset row : rows) {
            createTableRow(demoWorkBook, demoSheet, row, rowIndex);
            rowIndex++;
        }
        exportExcel(demoWorkBook, demoSheet);

    }

    //初始化表头信息
    public String[] initTabeleHeader() {
        String[] excelColumns = {"部门名称", "使用人", "资产编号", "资产名称", "规格型号", "单价", "品牌", "厂商", "购置日期", "保质期", "使用状况", "备注"};
        return excelColumns;
    }

    public static void createTableRow(HSSFWorkbook demoWorkBook, HSSFSheet demoSheet, Asset eit, int rowIndex) {
        //创建第rowIndex行
        CreationHelper createHelper = demoWorkBook.getCreationHelper();
        HSSFCellStyle dstyle = demoWorkBook.createCellStyle();
        HSSFCellStyle dstyles = demoWorkBook.createCellStyle();
        dstyles.setDataFormat(createHelper.createDataFormat().getFormat("yyyy年MM月dd日"));//格式
        dstyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.0"));


        HSSFCell cell = null;
        HSSFRow row = demoSheet.createRow(rowIndex);
        cell = row.createCell(0);
        cell.setCellValue(PayCodeConstants.convertString(eit.getDept().getName()));
        cell = row.createCell(1);
        cell.setCellValue(PayCodeConstants.convertString(eit.getPerson().getCpsn_name()));
        cell = row.createCell(2);
        cell.setCellValue(PayCodeConstants.convertString(eit.getAssetCode()));
        cell = row.createCell(3);
        cell.setCellValue(PayCodeConstants.convertString(eit.getAssetName()));
        cell = row.createCell(4);
        cell.setCellValue(PayCodeConstants.convertString(eit.getModel()));
        cell = row.createCell(5);
        cell.setCellValue(PayCodeConstants.convertDouble(eit.getPrice()));
        cell.setCellStyle(dstyle);
        cell = row.createCell(6);
        cell.setCellValue(PayCodeConstants.convertString(eit.getBrand()));
        cell = row.createCell(7);
        cell.setCellValue(PayCodeConstants.convertString(eit.getManufacture()));
        cell = row.createCell(8);
        cell.setCellValue(PayCodeConstants.convertDate(eit.getPurchDate()));
        cell.setCellStyle(dstyles);
        cell = row.createCell(9);
        if (eit.getShelfLife() == null) {
            cell.setCellValue("");
        } else {
            cell.setCellValue(PayCodeConstants.convertDate(eit.getShelfLife()));
            cell.setCellStyle(dstyles);
        }
        cell = row.createCell(10);
        cell.setCellValue(PayCodeConstants.convertString(PayCodeConstants.useStatus().get(eit.getUseStatus())));
        cell = row.createCell(11);
        cell.setCellValue(PayCodeConstants.convertString(eit.getMemo()));
    }

    public static void exportExcel(HSSFWorkbook demoWorkBook, HSSFSheet demoSheet) {
        try {
            String strfileName = "book.xls";
            FileOutputStream fos = null;
            //导出
            demoSheet.setGridsPrinted(true);//demoSheet
            HSSFFooter footer = demoSheet.getFooter();
            footer.setRight("Page " + HSSFFooter.page() + " of " + HSSFFooter.numPages());
            // 获得JSF上下文环境
            FacesContext context = FacesContext.getCurrentInstance();
            // 获得ServletContext对象
            ServletContext servletContext = (ServletContext) context.getExternalContext().getContext();
            // 取得文件的绝对路径
            String excelName = servletContext.getRealPath("/upload") + "/" + strfileName;//strfileName
            File exportFile = new File(excelName);
            fos = new FileOutputStream(exportFile);//fos
            demoWorkBook.write(fos);//demoWorkBook
            fos.close();

            FacesContext ctx = FacesContext.getCurrentInstance();
            ctx.responseComplete();
            HttpServletResponse httpServletResponse = (HttpServletResponse) ctx.getExternalContext().getResponse();
            ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
            httpServletResponse.setHeader("Content-disposition", "attachment; filename=" + strfileName);//strfileName
            httpServletResponse.setContentLength((int) exportFile.length());//exportFile
            httpServletResponse.setContentType("application/x-download");
            //httpServletResponse.setContentType("application/vnd.ms-excel");
            byte[] b = new byte[1024];
            int i = 0;
            FileInputStream fis = new java.io.FileInputStream(exportFile);
            while ((i = fis.read(b)) > 0) {
                servletOutputStream.write(b, 0, i);
            }
            servletOutputStream.flush();
            ctx.responseComplete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Asset getAsset() {
        return asset;
    }

    public void setAsset(Asset asset) {
        this.asset = asset;
    }

    public String getAssetName() {
        return assetName;
    }

    public void setAssetName(String assetName) {
        this.assetName = assetName;
    }

    public List<String> getAllAssetName() {
        return allAssetName;
    }

    public void setAllAssetName(List<String> allAssetName) {
        this.allAssetName = allAssetName;
    }

    public List<SelectItem> getSeleli() {
        return seleli;
    }

    public void setSeleli(List<SelectItem> seleli) {
        this.seleli = seleli;
    }

    public List<Asset> getAssetlist() {
        return assetlist;
    }

    public void setAssetlist(List<Asset> assetlist) {
        this.assetlist = assetlist;
    }
}
